import kkConfig from 'kkConfig'
import kkBaseData from 'kkBaseData'

let isLoadBgm = false

const soundWrapper = {
    audioBgmId: 0, // 记录背景音乐的音频 id
    soundEffectId: 0, // 最近加载的音效的 id
    bgm: null, // 背景音乐 cc.AudioClip
    effectMap: new Map(), // 音效 cc.AudioClip

    refreshSounds() {
        const { isOpenSound } = kkBaseData

        if (isOpenSound) {
            this.openBgm()
        } else {
            this.closeBgm()
            this.stopAllEffect()
        }

    },

    // 开启背景音乐
    openBgm() {
        const { bgmUrl, bgmVolume } = kkConfig.sound

        if (this.bgm) {
            this.audioBgmId = cc.audioEngine.playMusic(this.bgm, true, bgmVolume)
        } else if (isLoadBgm && !this.bgm) {
            let timer = setInterval(() => {
                if (this.bgm) {
                    this.audioBgmId = cc.audioEngine.playMusic(this.bgm, true, bgmVolume)
                    clearInterval(timer)
                }
            }, 300)
        } else {
            isLoadBgm = true
            cc.loader.loadRes(bgmUrl, cc.AudioClip, (err, bgm) => {
                if (err) {
                    cc.log('加载背景音乐失败，你不是当音乐家的料 ', err)
                    return
                }
                this.audioBgmId = cc.audioEngine.playMusic(bgm, true, bgmVolume)
                this.bgm = bgm
            })
        }
    },

    // 关闭背景音乐
    closeBgm() {
        cc.audioEngine.stopMusic()
    },

    // 播放音效
    playSoundEffect(audioUrl) {
        const { isOpenSound } = kkBaseData
        const { effectVolume } = kkConfig.sound

        if (!isOpenSound) {
            return
        }

        const effSource = this.effectMap.get(audioUrl)
        const isLoad = this.effectMap.get(audioUrl + '_is_load')

        if (effSource) {
            cc.audioEngine.playEffect(effSource, false, effectVolume)
        } else if (!effSource && isLoad) {
            let timer = setInterval(() => {
                const effSource = this.effectMap.get(audioUrl)
                if (effSource) {
                    cc.audioEngine.playEffect(effSource, false, effectVolume)
                    clearInterval(timer)
                }
            }, 300)
        } else {
            this.effectMap.set(audioUrl + '_is_load', true)
            cc.loader.loadRes(audioUrl, cc.AudioClip, (err, clip) => {
                if (err) {
                    cc.log('音效加载失败，错的是这个世界', err)
                    return
                }

                cc.audioEngine.playEffect(clip, false, effectVolume)
                this.effectMap.set(audioUrl, clip)
            })
        }

    },

    stopAllEffect() {
        cc.audioEngine.stopAllEffects()
    }

}

export default soundWrapper